//
//  GooGleAdMobMgr.m
//  WeCommunity
//
//  Created by mac on 2017/7/14.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "GooGleAdMobMgr.h"
#import "AdMobModel.h"

#define BIG_AD_KEY @"ca-app-pub-1438263689659228/6556198790"
#define NORMAL_AD_KEY @"ca-app-pub-1438263689659228/5079465591"

static GooGleAdMobMgr * gooGleAdMobMgr = nil;

@interface GooGleAdMobMgr ()<GADInterstitialDelegate>

@property(nonatomic,strong) GADInterstitial *interstitial;
@property(nonatomic,copy)   NSString *mobId;

@end

@implementation GooGleAdMobMgr

+(GooGleAdMobMgr *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        gooGleAdMobMgr = [[GooGleAdMobMgr alloc] init];
    });
    return gooGleAdMobMgr;
}

-(void)initAdMob
{
    self.mobId = BIG_AD_KEY;
    self.interstitial = [self createAndLoadInterstitial];
}

- (void)interstitialDidDismissScreen:(GADInterstitial *)interstitial {
    self.interstitial = [self createAndLoadInterstitial];
}

- (GADInterstitial *)createAndLoadInterstitial {
    
    GADInterstitial *interstitial = [[GADInterstitial alloc] initWithAdUnitID:self.mobId];
    interstitial.delegate = self;
    
    GADRequest *request =[GADRequest request];
    [interstitial loadRequest:request];
    return interstitial;
}

-(BOOL)showInterstitialWithVC:(UIViewController *)vc
{
    if(self.interstitial ==nil){
        return NO;
    }
    
    if ([UserInfoManger shared].userIsAdmin) {
        return NO;
    }
    
    if([UserInfoManger shared].isRemovedAD)
        return NO;
    
    
    if ([self.interstitial isReady]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.interstitial presentFromRootViewController:vc];
        });
        return YES;
    }
    return NO;
}

-(NSString *)normalAdKey
{
    if (!_normalAdKey) {
        _normalAdKey = NORMAL_AD_KEY;
    }
    return _normalAdKey;
}


#pragma mark - 加入广告数据
-(NSMutableArray *)getAdMobModelDataWithArray:(NSMutableArray *)array
{
    NSMutableArray * tempArray = [NSMutableArray array];
    NSInteger adMobFlag = 5;
    
    for (int i = 0; i < array.count ; i++) {
        if (![UserInfoManger shared].userIsAdmin && ![UserInfoManger shared].isRemovedAD) {
            if (i % adMobFlag == adMobFlag - 1) {
                [tempArray addObject:[AdMobModel new]];
            }
        }
        
        [tempArray addObject:array[i]];
        
    }
    if (![UserInfoManger shared].userIsAdmin && ![UserInfoManger shared].isRemovedAD) {
        if (array.count > 0 && array.count < adMobFlag) {
            [tempArray addObject:[AdMobModel new]];
        }
    }
    return tempArray;
}

@end
